package cn.like.satoken.core;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import cn.like.base.auth.AuthContext;
import cn.like.entity.AuthUser;
import cn.like.redis.RedisKey;
import cn.like.satoken.jwt.JwtManager;
import cn.like.util.BeanUtil;
import org.springframework.stereotype.Component;

/**
 * @author like 980650920@qq.com
 * @date 2021/7/10 13:22
 */
@Component
public class SaTokenAuthContext implements AuthContext<AuthUser> {

    private static final String KEY_TEMP_USER = "TEMP_USER:{0}";

    private final JwtManager jwtUtil;

    public SaTokenAuthContext(JwtManager jwtUtil) {this.jwtUtil = jwtUtil;}

    @Override
    public String doLogin(AuthUser user) {
        // 缓存一下当前用户
        SaManager.getSaTokenDao().set(RedisKey.of(KEY_TEMP_USER,user.getId()), JSONUtil.toJsonStr(user), 100);

        // 登录的时候会创建token，根据缓存的用户创建token TokenAction#createToken()
        StpUtil.login(user.getId());

        return StpUtil.getTokenValue();
    }

    @Override
    public AuthUser getUser() {
        return BeanUtil.copy(jwtUtil.getUser(),new AuthUser());
    }

    @Override
    public Long getUserId() {
        return getUser().getId();
    }

    @Override
    public String getName() {
        return getUser().getName();
    }
}
